package com.lee.demo1.business;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.lee.demo1.dao.InstructonsCategoryMapper;
import com.lee.demo1.dao.InstructonsImageMapper;
import com.lee.demo1.dao.InstructonsMapper;
import com.lee.demo1.dao.InstructonsTagMapper;
import com.lee.demo1.dao.TagMapper;
import com.lee.demo1.domain.Instructons;
import com.lee.demo1.domain.InstructonsCategory;
import com.lee.demo1.domain.InstructonsImage;
import com.lee.demo1.domain.Tag;

/**
 * 药品说明书业务类
 * @author leo
 *
 */
@Service
public class InstructonsBusiness {
	private static Logger logger = LoggerFactory.getLogger(InstructonsBusiness.class);
	
	@Resource
	private InstructonsMapper instructonsMapper;
	@Resource
	private InstructonsImageMapper imageMapper;
	@Resource
	private InstructonsCategoryMapper instructonsCategoryMapper;
	@Resource
	private TagMapper tagMapper;
	@Resource
	private InstructonsTagMapper instructonsTagMapper;
	
	@Value("${upload.images.dir}")
	private String uploadImagesDir;
	
	
	public String getUploadImagesDir() {
		return uploadImagesDir;
	}
	public void setUploadImagesDir(String uploadImagesDir) {
		this.uploadImagesDir = uploadImagesDir;
	}
	
	public Instructons getInstructons(int id){
		
		return instructonsMapper.selectByPrimaryKey(id);
		
	}
	
	/**
	 * 保存药品说明书 <br/>
	 * 1、保存文字信息<br/>
	 * 2、保存图片<br/>
	 * 3、保存图片路径信息<br/>
	 * 
	 * Mysql数据库在事物和自增长ID之间有冲突，在加上事务之后，取不到主表的自曾长编号<br/>
	 * @param instructons
	 * @return
	 */
	//@Transactional(propagation=Propagation.REQUIRED, isolation=Isolation.READ_COMMITTED, readOnly=false)  
	 //@Transactional(isolation = Isolation.SERIALIZABLE)
	//@Transactional(propagation = Propagation.REQUIRED,isolation=Isolation.REPEATABLE_READ)
	@SuppressWarnings("deprecation")
	public int saveInstructons(Instructons instructons,HttpServletRequest request){
		
		//1、保存说明书文字信息
		//keyProperty="id" useGeneratedKeys="true" 返回自增找ID必须在xml设置的属性
		int rtn = instructonsMapper.insert(instructons);
		logger.debug("------instructons.getId()---------" + instructons.getId());
		
		//2、上传图片，保存图片至upload目录下的，当前日期目录下
		List<InstructonsImage> imgList = new ArrayList<InstructonsImage>();
		MultipartHttpServletRequest mul = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = mul.getFiles("_img");
		
		for (int i = 0; i < files.size(); i++) {
			
			CommonsMultipartFile cmf = (CommonsMultipartFile) files.get(i);
			if(cmf.getSize()>0){
			
				String dir1 = cn.com.mylib.www.DateUtils.getSysDate("yyyyMMdd");
				String fileName =  String.valueOf(System.currentTimeMillis());
				
				StringBuilder newFileName = new StringBuilder();
				newFileName.append( request.getRealPath("/") )
						   .append( uploadImagesDir )
						   .append( File.separator )
						   .append( dir1 );
				
				//logger.debug( "---------------newFileName1 = " + newFileName.toString() );
				try {//创建目录
					FileUtils.forceMkdir(new File( newFileName.toString() ));
				} catch (IOException e1) {
					logger.error("-------------" + e1);
				}
				//logger.debug( "---------------newFileName2 = " + newFileName.toString() );
				newFileName.append( File.separator )
				   		   .append( fileName )
				   		   .append( FilenameUtils.EXTENSION_SEPARATOR_STR )
				   		   .append( FilenameUtils.getExtension( cmf.getOriginalFilename() ) );
				
				File file = new File( newFileName.toString());
				OutputStream os = null;
				try {
					os = new FileOutputStream( file );
					IOUtils.write( cmf.getBytes(), os );
				} catch (FileNotFoundException e) {
					logger.error("--------- FileNotFoundException" + e);
				} catch (IOException e) {
					logger.error("--------- IOException" + e);
				} finally {
					try {
						os.close();
					} catch (IOException e) {
						logger.error("--------- IOException" + e);
					}
				}
				//logger.debug( "---------------" + file.getAbsolutePath() );
				//logger.debug( "---------------" + cmf.getOriginalFilename() );
				
				//3、生成图片web路径，用于保存数据库中，用于页面显示
				StringBuilder webShowUrl = new StringBuilder();
				webShowUrl.append(uploadImagesDir)
						.append("/")
						.append(dir1)
						.append("/")
						.append( fileName )
				   		.append( FilenameUtils.EXTENSION_SEPARATOR_STR )
				   		.append( FilenameUtils.getExtension( cmf.getOriginalFilename() ) );
				
				InstructonsImage img = new InstructonsImage();
				img.setInstructonsId(instructons.getId());
				img.setImagePath(webShowUrl.toString() );
				imgList.add(img);
			}
		}
		//4、保存图片信息
		if(imgList.size()>0){
			imageMapper.insertInstructonsImageBatch(imgList);
		}
		//5、保存tag
		String[] tags = request.getParameterValues("tags");
		List<Map<String,Integer>> tagList = new ArrayList<Map<String,Integer>>();
		if(tags!=null && tags.length>0){
			for(int i=0; i<tags.length; i++){
				Map<String,Integer> map = new HashMap<String,Integer>();
				map.put("instructonsId", instructons.getId());
				map.put("tagId", Integer.parseInt(tags[i]));
				tagList.add(map);
			}
			instructonsTagMapper.insertTagsBatch(tagList);
		}
		
		return rtn;
	}
	
	/**
	 * 根据条件查询说明书列表，并分页
	 * @param map
	 * @return
	 */
	public List<Instructons> getInstructonsList(Map<String,Object> map){
		return instructonsMapper.selectByConditionsForPading(map);
	}
	
	/**
	 * 根据条件查询符合条件记录总数，用于分页
	 * @param map
	 * @return
	 */
	public int getInstructonsCount(Map<String,Object> map){
		return instructonsMapper.selectByConditionsCount(map);
	}
	
	/**
	 * 取出类别
	 * @return
	 */
	public List<InstructonsCategory> getInstructonsCategories(){
		return instructonsCategoryMapper.selectCategoriesAndSort();
	}
	
	public List<Tag> getTags(){
		return tagMapper.selectTagAndSort();
	}
}
